<template>
  <div class="app-container">
    <div class="table_container">
      <div class="table_top_btn">
        <div class="left_btn">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="openAddOrEdit(['repair', 'add'], {})"
            >{{ t("button.add") }}</el-button
          >
        </div>

        <right-toolbar
          @queryTable="queryList"
          :searchConfig="searchConfig"
          :columns.sync="columns"
          @search="handleSearch"
        >
        </right-toolbar>
      </div>

      <div class="table_area">
        <el-table
          height="100%"
          v-loading="loading"
          :data="repairData"
          :header-cell-style="{ textAlign: 'center' }"
          :cell-style="{ textAlign: 'center' }"
        >
          <el-table-column   :label="t('tableColumns.operation')"  align="center" fixed width="300">
            <template #default="{ row }">
              <div class="operate_link_btn">
                <el-link
                  type="primary"
                  :underline="false"
                  :icon="Document"
                  @click="startApply(row)"
                  :disabled="
                    row.enableFlag == 1 || row.enableFlag == 3 || row.enableFlag == 4
                      ? false
                      : true
                  "
                  >{{ t("button.apply") }}</el-link
                >
                <el-link
                  type="success"
                  :underline="false"
                  :icon="ArrowLeft"
                  @click="openAddOrEdit(['repair', 'return'], row)"
                  :disabled="row.RepairState == 2 || row.RepairState == 3 ? false : true"
                  >{{ t("button.return") }}</el-link
                >
                <el-link
                  type="warning"
                  :underline="false"
                  :icon="Edit"
                  @click="openAddOrEdit(['repair', 'edit'], row)"
                  :disabled="
                    row.enableFlag == 1 || row.enableFlag == 3 || row.enableFlag == 4
                      ? false
                      : true
                  "
                  >{{ t("button.edit") }}</el-link
                >
                <el-link
                  type="danger"
                  :underline="false"
                  :icon="Delete"
                  @click="revokeRepair(row)"
                  :disabled="row.enableFlag == 1 || row.enableFlag == 4 ? false : true"
                  >{{ t("button.void") }}</el-link
                >
              </div>
            </template>
          </el-table-column>

          <template v-for="(item, index) in columns" :key="item.key">
            <el-table-column
              v-if="item.visible"
              :prop="item.prop"
               :label="t(`tableColumns.${item.langKey}`)"
              :width="item.width"
              :show-overflow-tooltip="true"
            >
              <template #default="{ row }">
                <div
                  v-if="item.prop == 'repairNo'"
                  :style="{
                    color: colors.primaryColor,
                    cursor: item.isclick ? 'pointer' : '',
                  }"
                  @click="openAddOrEdit(['repair', 'detail'], row)"
                >
                  {{ row.repairNo }}
                </div>

                <el-tag
                  v-else-if="item.prop == 'enableFlag'"
                  :type="
                    row.enableFlag == 0
                      ? 'danger'
                      : row.enableFlag == 1
                      ? 'warning'
                      : row.enableFlag == 3
                      ? 'primary'
                      : 'success'
                  "
                  >{{
                    filterStatus(row.enableFlag, "documentStatus", "id", "langKey") ||
                    "无"
                  }}</el-tag
                >
                <el-tag
                  v-else-if="item.prop == 'RepairState'"
                  :type="
                    row.RepairState == 2 || row.RepairState == 0
                      ? 'danger'
                      : row.RepairState == 1
                      ? 'warning'
                      : row.RepairState == 3
                      ? ''
                      : 'success'
                  "
                >
                  {{
                    filterStatus(row.RepairState, "repairStatus", "id", "langKey") || "无"
                  }}</el-tag
                >
                <span v-else-if="item.prop == 'createDate' || item.prop == 'repairDate'">
                  {{ parseTime(row[item.prop], "{y}-{m}-{d}") || "无" }}
                </span>
                <span v-else>{{ row[item.prop] || "无" }}</span>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </div>
      <div class="pagination-area">
        <pagination
          :total="page.total"
          v-model:page="page.pageNum"
          v-model:limit="page.pageSize"
          @pagination="queryList"
        />
      </div>
    </div>
    <addOrEdit
      v-if="operate.openObj.visible"
      ref="addOrEditDialogRef"
      v-model:add-edit-info="operate"
      @getCanUseAssetsData="queryCanUseAssetsData"
      @returnAssets="retrunSubmit"
      @submitAddEditInfo="submit"
      @cancelAddEditInfo="cancel"
    ></addOrEdit>
  </div>
</template>

<script setup name="AssetisList">
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import colors from "@/assets/styles/variables.module.scss";
import { Edit, ArrowLeft, Delete, Document } from "@element-plus/icons-vue";
import RightToolbar from "@/components/RightToolbar";

import addOrEdit from "@/components/AshDialog/addOrEdit.vue";
import { assetsColums, repairColums } from "@/utils/table/columns";
import { documentStatus, repairStatus } from "@/utils/statuData";
import {
  GetAssetsRepairList,
  AddAssetsRepair,
  getAssetsRepairDetail,
  getAssetsCanRepair,
  SaveRepairReturn,
  RepairAssetsRevoke,
} from "@/api/assetsManage/repair";
import { AddDocumentApply } from "@/api/assetsManage/apply";
import { GetUserInfoAll } from "@/api/sys/user";
import { getUserInfo } from "@/utils/auth";
import { ElMessage, ElMessageBox } from "element-plus";
const { proxy } = getCurrentInstance();
const filterRepairStatus = proxy.getTranslatedOptions(repairStatus);
const { AssetClassification } = proxy.useDict("AssetClassification");

const repairData = ref([]); //维修列表
const loading = ref(false);
const columns = repairColums;
const page = reactive({
  total: 0,
  pageNum: 1,
  pageSize: 100,
});
const users = ref([]);
const selectedOrganization = ref(null);
const dates = ref(proxy.getDefault30DaysRange());
const handleClearRepairState = (value) => {
  value ? value : (searchConfig.value.form.RepairState = -1);
};
const searchConfig = ref({
  form: {
    Dates: dates.value ? dates.value : ["", ""],
    RepairState: -1,
  },
  formItems: [
    {
      label: t("assetsFix.fixType"),
      prop: "RepairState",
      type: "el-select",
      attrs: {
        clearable: false,
        placeholder: t("assetsFix.fixTypePlaceholder"),
      },
      options: filterRepairStatus,
      optionProps: {
        key: "id",
        label: "label",
        value: "id",
      },
      events: {
        clear: handleClearRepairState,
      },
    },
    {
      label: t("assetsList.assetCode"),
      prop: "assetsCode",
      type: "el-input",
      attrs: {
        clearable: true,
        placeholder: t("assetsList.assetCodePlaceholder"),
      },
    },
    {
      label: t("assetsList.assetName"),
      prop: "assetsName",
      type: "el-input",
      attrs: {
        clearable: true,
        placeholder: t("assetsList.assetNamePlaceholder"),
      },
    },
    {
      label: t("assetsList.assetType"),
      prop: "assetsClassifyId",
      type: "el-select",
      attrs: {
        clearable: true,
        placeholder: t("assetsList.assetTypePlaceholder"),
      },
      options: AssetClassification,
      optionProps: {
        key: "dictionaryKey",
        label: "dictionaryName",
        value: "dictionaryCode",
      },
      events: {},
    },
    {
      label: t("assetsList.useUser"),
      prop: "useUserName",
      type: "el-input",
      attrs: { clearable: true, placeholder: "请输入使用人员" },
      events: {},
    },
    {
      label: t("assetsList.model"),
      prop: "specModel",
      type: "el-input",
      attrs: { clearable: true, placeholder: t("assetsList.modelPlaceholder") },
    },
    {
      label: t("assetsFix.fixDate"),
      prop: "Dates",
      type: "el-date-picker",
      attrs: {
        valueFormat: "YYYY-MM-DD",
        "range-separator": t("common.to"),
        "start-placeholder": t("common.startDate"),
        "end-placeholder": t("common.endDate"),
        clearable: true,
        type: "daterange",
        "default-time": dates.value,
      },
    },
  ],
  rules: {},
});

const canUseAssetsInfo = reactive({
  data: [],
  page: {
    total: 0,
    pageNum: 1,
    pageSize: 100,
  },
  loading: false,
  searchInfo: searchConfig,
}); // 传给孙组件的资产数据
provide("canUseAssetsInfo", canUseAssetsInfo);

const handleRepairCostInput = (value) => {
  operate.formInfo.repairCost = proxy.costInput(value);
};
const operate = reactive({
  openObj: {
    visible: false,
    openKey: "", //add edit detail
    openType: "", //维修 报废 退还 领用....
    openTitle: "",
    tableTitle: "",
    addLoading: false, //防止重复提交
  },
  formInfo: {
    applicantUserId: "",
    repairContent: "",
    repairCost: "",
    repairDate: "",
  },
  formItems: [
    {
      label: t("assetsFix.fixUser"),
      prop: "applicantUserId",
      type: "el-select",
      span: 12,
      attrs: {
        clearable: true,
        disabled: false,
        placeholder: t("assetsFix.fixTypePlaceholder"),
      },
      events: {},
      options: users,
      optionProps: {
        key: "userId",
        label: "userName",
        value: "userId",
      },
      filterable: true,
      rules: [
        {
          required: true,
          message: t("assetsFix.fixTypeRuleErrorTip"),
          trigger: "change",
        },
      ],
    },
    {
      label: t("assetsFix.fixContent"),
      prop: "repairContent",
      type: "el-input",
      span: 12,
      attrs: {
        clearable: true,
        disabled: false,
        placeholder: t("assetsFix.fixContentPlaceholder"),
      },
      events: {},
      // rules: [{ message: '请输入维修内容' }],
    },
    {
      label: t("assetsFix.fixCost"),
      prop: "repairCost",
      type: "el-input",
      span: 12,
      attrs: {
        clearable: true,
        disabled: false,
        placeholder: t("assetsFix.fixCostPlaceholder"),
      },
      events: {
        input: (event) => handleRepairCostInput(event),
      },
      rules: [],
    },
    {
      label: t("assetsFix.fixDate"),
      prop: "repairDate",
      type: "el-date-picker",
      span: 12,
      attrs: {
        type: "date",
        "value-format": "YYYY-MM-DD",
        "disabled-date": (date) => proxy.dateAfterToday(date, true),
        clearable: false,
        disabled: false,
        placeholder: t("assetsFix.fixDatePlaceholder"),
      },
      events: {},
      rules: [
        {
          required: true,
          message: t("assetsFix.fixDateRuleErrorTip"),
          trigger: "change",
        },
      ],
    },
    {
      label: t("assetsFix.fixRemark"),
      prop: "repairRemark",
      type: "el-input",
      span: 24,
      attrs: {
        clearable: true,
        disabled: false,
        placeholder: t("assetsFix.fixRemarkPlaceholder"),
      },
      events: {},
      rules: [],
    },
  ],
  loadingUser: false,
  tableData: [], //表格数据，添加的时候为空，其他情况为查询赋值
  toBeDelData: [], //需要移除的数据
  delList: [], //删除数据
});

//1111获取列表
const queryList = () => {
  const { Dates, ...rest } = searchConfig.value.form;
  const [StartDate, EndDate] = Dates || ["", ""];
  const params = {
    pagination: page.pageNum - 1,
    pageRow: page.pageSize,
    isInit: true,
    ...rest,
    StartDate,
    EndDate,
  };
  loading.value = true;
  GetAssetsRepairList(params)
    .then((res) => {
      loading.value = false;
      repairData.value = res.output.output;
      page.total = res.output.count;
    })
    .catch((err) => {
      loading.value = false;
    });
};

//获取人员,必须先选择使用组织
const queryAllUsers = (organizeId) => {
  operate.loadingUser = true;
  GetUserInfoAll({
    subordinateDepartmentId: organizeId,
  })
    .then((res) => {
      users.value = res.output;
      operate.loadingUser = false;
    })
    .catch((err) => {
      users.value = [];
      operate.loadingUser = false;
    });
};

//查询单据详情
const queryAssetsDetail = (repairId) => {
  getAssetsRepairDetail({ repairNo: repairId }).then((res) => {
    operate.tableData = res.output;
  });
};
//222添加修改相关
const openAddOrEdit = (typeKey, row) => {
  const type = typeKey[0];
  const key = typeKey[1];
  const title =
    key == "add"
      ? t("assetsFix.addFixDialogTitle")
      : key == "edit"
      ? t("assetsFix.editFixDialogTitle")
      : key == "return"
      ? t("assetsFix.returnFixDialogTitle")
      : t("assetsFix.viewFixDialogTitle");
  operate.openObj = {
    visible: true,
    openKey: key,
    openType: type,
    openTitle: title,
    tableTitle: t("assetsFix.fixAssets"),
    addLoading: false,
  };
  operate.formInfo = {
    repairDate: proxy.getNowDate(),
    ...row,
  };
  operate.tableData = [];
  operate.toBeDelData = [];
  if (key != "add") {
    queryAssetsDetail(row.repairNo);
  }
};

//添加维修单的提交
const submit = async (info) => {
  const sub = info.infoSub.map((item, index) => {
    return {
      assetsId: item.assetsId,
      assetsName: item.assetsName,
      rowId: index,
      state: item.state ? item.state : 0,
    };
  });
  const delSub = info.delSub.map((item, index) => {
    return {
      assetsId: item.assetsId,
      assetsName: item.assetsName,
      rowId: index,
      state: item.state,
    };
  });
  if (sub.length == 0) {
    ElMessage({ message: t("common.pleaseSelectAssets"), type: "warning" });
    return;
  }

  operate.openObj.addLoading = true;
  const formAdd = {
    ...info.info,
    createUserId: JSON.parse(getUserInfo()).userId,
    createUser: JSON.parse(getUserInfo()).userName,
  };
  const formEdit = {
    ...info.info,
    updateUserId: JSON.parse(getUserInfo()).userId,
    updateUser: JSON.parse(getUserInfo()).userName,
  };
  let params = {
    Info: operate.openObj.openKey == "add" ? formAdd : formEdit,
    InfoSub: operate.openObj.openKey == "add" ? sub : sub.concat(delSub),
  };
  console.log("参数2", params.InfoSub);
  const msg = operate.openObj.openKey == "add" ? t("button.add") : t("common.cancel");

  try {
    await AddAssetsRepair(params).then((res) => {
      ElMessage({
        message: `${t("assetsFix.fixDocument")}:${res.output}${msg}${t(
          "common.success"
        )}`,
        type: "success",
      });
    });
    await cancel();
    await queryList();
  } catch (error) {
    operate.openObj.addLoading = false;
  }
};
//取消添加
const cancel = () => {
  operate.openObj.visible = false;
};
//发起申请
const startApply = (row) => {
  const params = {
    fieldNo: row.repairNo,
    fieldType: 1,
  };
  AddDocumentApply(params)
    .then((res) => {
      ElMessage({
        message: t("message.approvalStartedSuccess"),
        type: "success",
      });
      queryList();
    })
    .catch((err) => {
      console.error(err);
    });
};
//返还维修单
const retrunSubmit = (row) => {
  const { info, infoSub } = row;
  let params = {
    repairNo: info.repairNo,
    updateUser: JSON.parse(getUserInfo()).userName,
    updateUserId: JSON.parse(getUserInfo()).userId,
  };

  if (infoSub.length == 0) {
    ElMessage({
      message: t("assetsFix.returnAssetsSelectTip"),
      type: "warning",
    });
    return;
  }
  ElMessageBox.confirm(
    `${t("assetsFix.confirmReturnRepairTip")}${info.repairNo}`,
    t("message.tip"),
    {
      confirmButtonText: t("common.confirm"),
      cancelButtonText: t("common.cancel"),
      type: "warning",
    }
  ).then(() => {
    SaveRepairReturn({ Info: params, InfoSub: infoSub })
      .then((res) => {
        ElMessage({
          type: "success",
          message: t("assetsFix.returnFixSuccess"),
        });
        cancel();
        // queryAssetsDetail(info.repairNo)
        queryList();
      })
      .catch((err) => {
        console.log(err);
      });
  });
};
//作废维修单
const revokeRepair = (row) => {
  const params = {
    repairNo: row.repairNo,
    userId: JSON.parse(getUserInfo()).userId,
  };
  ElMessageBox.confirm(
    `${t("message.confirmVoidDocument")}:${row.repairNo}`,
    t("message.tip"),
    {
      confirmButtonText: t("common.confirm"),
      cancelButtonText: t("common.cancel"),
      type: "warning",
    }
  )
    .then(() => {
      RepairAssetsRevoke(params)
        .then((res) => {
          ElMessage({ message: t("message.voidSuccess"), type: "success" });
          queryList();
        })
        .catch((err) => {
          console.log("失败", err);
        });
    })
    .catch(() => {});
};

///3333高级搜索的
//确定高级搜索
const handleSearch = async (info) => {
  await queryList();
};

//44444444孙组件的列表数据
const queryCanUseAssetsData = () => {
  canUseAssetsInfo.loading = true;
  let params = {
    pagination: canUseAssetsInfo.page.pageNum - 1,
    pageRow: canUseAssetsInfo.page.pageSize,
    isInit: true,
    enableFlag: 3,
    ...canUseAssetsInfo.searchInfo.form,
  };
  getAssetsCanRepair(params)
    .then((res) => {
      canUseAssetsInfo.data = res.output.output;
      canUseAssetsInfo.page.total = res.output.count;
      canUseAssetsInfo.loading = false;
    })
    .catch(() => {
      canUseAssetsInfo.data.value = [];
      canUseAssetsInfo.loading = false;
    });
};

onMounted(() => {
  queryList();
  queryAllUsers("");
});
</script>
<style lang="scss" scoped></style>
